package cn.edu.swu.book;

import cn.edu.swu.core.BasicServlet;
import cn.edu.swu.core.JsonResponseWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet(urlPatterns = "/api/book/*")
public class BookApi  extends BasicServlet {

    private BookService bookService = null;

    public void init(ServletConfig config) {
        BookRepo repo = new BookRepo();
        bookService = new BookService();
        bookService.setRepo(repo);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        this.methodRoute(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        this.methodRoute(request, response);
    }

    private void methodRoute(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        String uri = request.getRequestURI();
        String method = uri.substring(uri.lastIndexOf("/") + 1);
        if (method.equals("list")) {
            this.list(request, response);
        } else if (method.equals("add")) {
            this.add(request, response);
        }
    }

    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException{
        try {
            List<Book> books = this.bookService.getAll();
            this.responseJson(response, true, books);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException{
        try {
            String json = this.getRequestBody(request);
            System.out.println(json);
            objectMapper.setDateFormat(dateFormatter);
            Book book = objectMapper.readValue(json, Book.class);
            this.bookService.save(book);
            this.responseJson(response, true, book);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}




